package admin

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/grpool"
	"github.com/gogf/gf/v2/util/gconv"
	"miaoyu/internal/dao"
	modelAdmin "miaoyu/internal/model/admin"
	"miaoyu/internal/model/entity"
	"miaoyu/internal/service"
	"miaoyu/internal/utility/utils"
)

/*
@Time : 2023/1/30 17:23
@Author : licxpro
@File : log.logic.go
*/
type sLog struct {
	Pool *grpool.Pool
}

func init() {
	service.RegisterLog(NewLog())
}

func NewLog() *sLog {
	return &sLog{
		Pool: grpool.New(68),
	}
}

// MiddleWareFunc 日志中间件 位于鉴权之后
func (s *sLog) MiddleWareFunc(r *ghttp.Request) {
	ctx := r.Context()
	s.Pool.Add(ctx, func(ctx context.Context) {
		//fmt.Println(r.Request)
		params := r.GetQueryMap()
		form := r.GetFormMap()
		//header := r.Header
		url := r.Request.URL.String()
		ip := utils.GetClientIp(ctx)
		user := service.Session().GetUser(ctx)
		data := modelAdmin.OperateLogItem{
			UserId:   user.Id,
			Username: user.UserName,
			Ip:       ip,
			Path:     url,
			//Headers:  gconv.String(header),
			Params: gconv.String(params),
			Forms:  gconv.String(form),
			Method: r.Method,
		}

		s.operationLogAdd(ctx, &data)
	})
}

// OperationLogAdd 添加操作日志
func (s *sLog) operationLogAdd(ctx context.Context, data *modelAdmin.OperateLogItem) {
	_, err := dao.MyLogOperation.Ctx(ctx).Save(data)
	if err != nil {
		g.Log().Error(ctx, err, data)
	}
}

// LoginLogAdd 登陆操作日志
func (s *sLog) LoginLogAdd(ctx context.Context, data entity.MyLogLogin) {

	_, err := dao.MyLogLogin.Ctx(ctx).Save(data)
	if err != nil {
		g.Log().Error(ctx, err, data)
	}
}
